﻿using System;
using System.IO.IsolatedStorage;
using Caliburn.Micro;
using FinalCountdownServices;
using FinalCountdownServices.Models;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace FinalCountdown.ViewModels
{
    public enum ModeType
    {
        Create,
        Modify
    }

    public class CreateOrModifyEventPageViewModel : Screen
    {
        #region ctor + private fields

        private readonly INavigationService _navigationService;
        private readonly IEventService _eventService;
        private readonly ITileService _tileService;
        private EventHandler<PhotoResult> _photoResultHandler;
        private EventModel _event;
        private PhotoChooserTask _selectphoto = null;

        //private BitmapImage _myBg;

        public CreateOrModifyEventPageViewModel(INavigationService navigationService, 
            IEventService eventService, ITileService tileService)
        {
            _navigationService = navigationService;
            _eventService = eventService;
            _tileService = tileService;
            _photoResultHandler = (sender, e) =>
            {
                if (e.TaskResult == TaskResult.OK)
                {
                    BackgroundSource = new Uri("isostore:/Shared/ShellContent/FinalCountdownBg_tmp_" + (_event != null ? _event.Id : _eventService.GetNextId()) + ".jpg", UriKind.Absolute);
                    CanSelectImage = true;
                    NotifyOfPropertyChange(() => CanSelectImage);
                    var b = new WriteableBitmap(173, 173);
                    b.SetSource(e.ChosenPhoto);
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        var filename = "/Shared/ShellContent/FinalCountdownBg_tmp_" + (_event != null ? _event.Id : _eventService.GetNextId()) + ".jpg";
                        using (var st = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.Write, store))
                        {
                            b.SaveJpeg(st, 173, 173, 0, 100);
                        }
                    }
                    PhotoSelected = true;
                    NotifyOfPropertyChange(() => PhotoSelected);
                }
            };
        }

        #endregion

        #region properties

        public ModeType Mode { get; set; }
        public int EventId { get; set; }

        #endregion

        #region VM properties

        public bool PhotoSelected { get; set; }

        public bool CanSelectImage { get; set; }

        public bool CanSave
        {
            get
            {
                return !string.IsNullOrEmpty(Title) && Occurs != null && Occurs > DateTime.Now;
            }
        }

        private string _imgSrc;
        public string ImgSrc
        {
            get { return _imgSrc; }
            set
            {
                if (_imgSrc == value) return;
                _imgSrc = value;
                NotifyOfPropertyChange(() => ImgSrc);
            }
        }

        private Uri _backgroundSource;
        public Uri BackgroundSource
        {
            get { return _backgroundSource; }
            set
            {
                if (_backgroundSource == value) return;
                _backgroundSource = value;
                NotifyOfPropertyChange(() => BackgroundSource);
            }
        }
        

        private string _saveButtonText;
        public string SaveButtonText
        {
            get { return _saveButtonText; }
            set
            {
                if (_saveButtonText == value) return;
                _saveButtonText = value;
                NotifyOfPropertyChange(() => SaveButtonText);
            }
        }

        private bool _isNotificationEnabled;
        public bool IsNotificationEnabled
        {
            get { return _isNotificationEnabled; }
            set
            {
                if (_isNotificationEnabled == value) return;
                _isNotificationEnabled = value;
                NotifyOfPropertyChange(() => IsNotificationEnabled);
            }
        }

        private int _notificationMinutes;
        public int NotificationMinutes
        {
            get { return _notificationMinutes; }
            set
            {
                if (_notificationMinutes == value) return;
                _notificationMinutes = value;
                NotifyOfPropertyChange(() => NotificationMinutes);
            }
        }
        
        private string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                if (_title == value) return;
                _title = value;
                NotifyOfPropertyChange(() => Title);
                NotifyOfPropertyChange(() => CanSave);
            }
        }

        private string _description;
        public string Description
        {
            get { return _description; }
            set
            {
                if (_description == value) return;
                _description = value;
                NotifyOfPropertyChange(() => Description);
            }
        }

        private DateTime? _occurs;
        public DateTime? Occurs
        {
            get { return _occurs; }
            set
            {
                if (_occurs == value) return;
                _occurs = value;
                NotifyOfPropertyChange(() => Occurs);
                NotifyOfPropertyChange(() => CanSave);
            }
        }

        #endregion

        #region Init

        protected override void OnActivate()
        {
            base.OnActivate();
            if (Mode == ModeType.Create)
            {
                SetupForCreation();
            }
            else
            {
                SetupForModification();
            }
        }

        private void SetupForModification()
        {
            DisplayName = "Esemény módosítása";
            SaveButtonText = "Módosítások mentése";
            _event = _eventService.GetEvent(EventId);
            Title = _event.Title;
            Description = _event.Description;
            Occurs = (DateTime?)_event.Occurs;
            NotificationMinutes = _event.NotificationMinutes;
            IsNotificationEnabled = _event.NotificationEnabled;
            PhotoSelected = _event.BackgroundSource != null;
            NotifyOfPropertyChange(() => PhotoSelected);
            CanSelectImage = true;
            NotifyOfPropertyChange(() => CanSelectImage);
        }

        private void SetupForCreation()
        {
            DisplayName = "Új esemény létrehozása";
            SaveButtonText = "Létrehozás";
            NotificationMinutes = 1;
            Occurs = (DateTime?)DateTime.Now.AddDays(1);
            CanSelectImage = true;
            NotifyOfPropertyChange(() => CanSelectImage);
        }

        #endregion

        public void SelectImage()
        {
            CanSelectImage = false;
            NotifyOfPropertyChange(() => CanSelectImage);
            _selectphoto = new PhotoChooserTask();
            _selectphoto.Completed += _photoResultHandler;
            _selectphoto.Show();
        }

        public void Save()
        {
            if (Mode == ModeType.Create)
            {
                var myEvent = new EventModel
                {
                    Description = this.Description,
                    Occurs =this.Occurs.Value,
                    NotificationMinutes = this.NotificationMinutes,
                    TileEnabled = false,
                    Title = this.Title,
                    NotificationEnabled = this.IsNotificationEnabled,
                    BackgroundSource = BackgroundSource,
                };
                _eventService.AddEvent(myEvent);
                _navigationService.GoBack();
            }
            else
            {
                _event.Occurs = this.Occurs.Value;
                _event.Description = this.Description;
                _event.NotificationMinutes = this.NotificationMinutes;
                _event.Title = this.Title;
                _event.NotificationEnabled = this.IsNotificationEnabled;
                _event.BackgroundSource = BackgroundSource;
                _eventService.ModifyEvent(_event);
                if (_event.TileEnabled)
                {
                    _tileService.AddOrModifyTileByEvent(_event);
                }
                _navigationService.GoBack();
            }
        }
    }
}
